import Vue from 'vue'
import VueRouter from 'vue-router'
import { Toast } from 'vant';

Vue.use(Toast);

Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    name: 'index',
    meta: { title: "饿了么-首页" },
    component: () => import('../views/Index.vue'),
    children: [
      {
        path: '/index/home',
        name: 'home',
        meta: { title: "饿了么-首页" },
        component: () => import('../views/Index/Home.vue')
      },
      {
        path: '/index/mine',
        name: 'mine',
        meta: { title: "饿了么-我的" },
        component: () => import('../views/Index/Mine.vue')
      },
      {
        path: '/index/order',
        name: 'order',
        meta: { title: "饿了么-我的订单" },
        component: () => import('../views/Index/Order.vue')
      },
      {
        path: '/index/tuan',
        name: 'tuan',
        meta: { title: "饿了么-爆爆团" },
        component: () => import('../views/Index/Tuan.vue')
      },
      {
        path: '/index',
        redirect: '/index/home'
      }
    ]
  },
  {
    path: '/detail/:id',
    name: 'detail',
    meta: { title: "饿了么-详情页" },
    component: () => import('../views/Detail.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta: { title: "饿了么-登录" },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/collect',
    name: 'collect',
    meta: { title: "饿了么-我的收藏" },
    component: () => import('../views/Collect.vue')
  },
  {
    path: '/register',
    name: 'register',
    meta: { title: "饿了么-注册" },
    component: () => import('../views/Register.vue')
  },
  {
    path: '/search',
    name: 'search',
    meta: { title: "饿了么-搜索" },
    component: () => import('../views/Search.vue')
  },
  {
    path: '/address',
    name: 'address',
    meta: { title: "收货地址" },
    component: () => import('../views/ShopAddress.vue')
  },
  {
    path: '/add_address',
    name: 'add_address',
    meta: { title: "新增收货地址" },
    component: () => import('../views/Add_address.vue')
  },
  {
    path: '/edit_address',
    name: 'edit_address',
    meta: { title: "修改地址" },
    component: () => import('../views/EditAddress.vue')
  },
  {
    path: '/searchkey/:key',
    name: 'searchkey',
    meta: { title: "搜索" },
    component: () => import('../views/Searchkey.vue')
  },
  {
    path: '/pay',
    name: 'pay',
    meta: { title: "支付订单" },
    component: () => import('../views/Pay_order.vue')
  },
  {
    path: '/',
    redirect: "/index"
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {


  document.title = to.meta.title
  let token = localStorage.getItem('token')
  if (to.path == '/index/mine') {
    if (token) {
      next();
    } else {
      Toast('还未登录，请先登录');
      next('/login')

    }
  } else if (to.path == '/index/order') {
    if (token) {
      next();
    } else {
      Toast('还未登录，请先登录');
      next('/login')

    }
  }
  else {
    next();
  }
})

export default router
